import React, { useEffect, useState } from 'react';
import { Input, message, Upload, Modal, Button } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import MdEditor from 'md-editor-rt';
import intl, { init } from 'react-intl-universal';
import $ from 'jquery';
import { storage } from '../../utils/localstorage.js';
import ArticleClassify from './articleClassify.js';
import 'md-editor-rt/lib/style.css';


const getBase64 = (file) =>                                     // 将图片转为 base64字节编码 编码成的字节数据
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });


const ArticleUpdate = (props) => {
  let initData = {
    id: -1,
    title: null,
    summary: null,
    text: '',
    cover: null,
    author: storage.get('user').username,
    kind: null,
  };
  if (props.data !== null && props.data !== undefined) {
    initData = {
      id: props.data.id,
      title: props.data.title,
      summary: props.data.summary,
      text: props.data.text,
      cover: props.data.cover,
      author: props.data.author,
      kind: props.data.kind,
    };
  }

  // 文章标题、概述、详细内容
  const [title, setTitle] = useState(initData.title);                        // 文章标题
  const [summary, setSummary] = useState(initData.summary);                  // 文章概述
  const [kind, setKind] = useState(initData.kind);                           // 文章分类
  const [text, setText] = useState(initData.text);                           // 详细内容

  const titleChange = (event) => {
    setTitle(event.target.value);
  };

  const summaryChange = (event) => {
    setSummary(event.target.value);
  };


  // 上传封面
  const [previewVisible, setPreviewVisible] = useState(false);  // 标识是否显示大图预览Modal
  const [previewImage, setPreviewImage] = useState();           // 大图的URL
  const [fileList, setFileList] = useState([]);                 // 所有已上传图片文件对象的数组

  const handleCancel = () => setPreviewVisible(false);          // 隐藏大图预览modal

  const handlePreview = async (file) => {                       // 预览大图图片
    if (!file.url && !file.preview) {                           // url:undefined，会被转换为true。 preview:有值
      file.preview = await getBase64(file.originFileObj);       // originFileObj：有值。只有通过getBase64()才能预览
    }
    setPreviewImage(file.url || file.preview);                  // 将图片数据存入previewImage
    setPreviewVisible(true);  
  };

  const handleChange = async ({ fileList: newFileList }) => {
    if (newFileList[0] !== undefined) {
      let temp = await getBase64(newFileList[0].originFileObj); // 图片数据存入previewImage
      setPreviewImage(temp);
    }
    setFileList(newFileList);
  };

  const [size, setSize] = useState(true);

  const beforeUpload = (file) => {                              // 限制图片格式和大小
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.info('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      setSize(false);
      message.error('Image must smaller than 2MB!');
    }
    return false;
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{marginTop: 8,}}>Upload</div>
    </div>
  );


  // 发布文章
  const handleSubmit = () => {
    if (!size) {                                                // 封面图片大小校验，不超过2MB
      setSize(true);
      message.error('Image must smaller than 2MB!');
      return;
    }

    let data = {                                                // 文章相关内容
      aid: initData.id,
      title: title,
      summary: summary,
      kind: kind,
      author: initData.author,
      content: text,
      cover: previewImage,
    };

    if (data.cover === undefined || data.cover === null || data.cover === '') {
      data.cover = initData.cover;
    }

    if ((data.summary === undefined || data.summary === null || data.summary === '')
        && (data.content !== undefined && data.content !== null)) {   // 若不写文章概述，则自动截取文章前面部分作为概述
      if (data.content.length > 128) {
        data.summary = data.content.substring(0, 126) + '……';
      } else {
        data.summary = data.content.substring(0, data.content.length);
      }
    }

    if (data.title === undefined || data.title === null || data.title === '' || 
    data.author === undefined || data.author === null || data.author === '') {          // 校验标题不为空
      message.error('标题不能为空');
      return;
    }

    // console.log('update',data);

    $.ajax({
      url: '/home/article/update',
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(result) {
        if (result.status === 1) {
          message.success('发布成功');
          props.closeDrawer();
          props.setHasChange(true);
        } else {
          message.error('发布失败，请稍后再试');
        }
      },
      error: function(err) {
        alert(JSON.stringify(err));
      },
    });
  };


  return (
    <div>
      <Input maxLength={'128'} placeholder={'请输入文章标题（不超过128个字）'} value={title} showCount={true} 
        style={{marginBottom: '10px', width: '45%', }} onChange={titleChange} />
      <MdEditor modelValue={text} onChange={setText} preview={false} style={{marginBottom: '20px'}} />
      <span style={{fontSize: '16px'}}>封面&摘要：</span>
      <div style={{display: 'flex'}}>
        <Upload className='uploadCover' listType="picture-card" beforeUpload={beforeUpload} onPreview={handlePreview} onChange={handleChange}>
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} header={null} footer={null} onCancel={handleCancel}>
          <img alt="example" style={{width: '100%',}} src={previewImage} />
        </Modal>
        <Input.TextArea maxLength={'128'} placeholder={'请输入文章摘要'} value={summary} showCount={true} 
          style={{marginBottom: '10px', width: '50%', height: '104px'}} rows={'4'} onChange={summaryChange} />
      </div>
      <span style={{fontSize: '16px'}}>分类：</span>
      <div>
        <ArticleClassify setKind={setKind} kind={kind} />
      </div>
      <Button type='primary' className='submitArticle' onClick={handleSubmit}>{intl.get('submit')}</Button>
    </div>
  );
};

export default ArticleUpdate;